package com.sxf.controller.blog;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.sxf.common.tools.WPConstants;
import com.sxf.common.tools.WebTools;
import com.sxf.controller.formbean.PostVO;
import com.sxf.domain.Comment;
import com.sxf.domain.Post;
import com.sxf.domain.User;
import com.sxf.querybean.PostQuery;
import com.sxf.service.CommentService;
import com.sxf.service.PostService;
import com.sxf.service.UserService;

@Controller("showCommentController")
@RequestMapping("blog")
public class CommentController extends MultiActionController {
	@Resource
	private PostService postService;

	@Resource
	private UserService us;

	@Resource
	private CommentService commentService;

	@RequestMapping("/comment")
	@ResponseBody
	public String addComment(@RequestParam("postId") String pid)
			throws Exception {
		Comment comment = new Comment();
		comment.setApproved("0");
		Date date = new Date();
		comment.setDate(date);
		comment.setDateGmt(date);
		// TODO
		Long postId = Long.parseLong(pid);
		PostQuery postQuery = new PostQuery();
		postQuery.setId(postId);
		List<PostVO> postList = postService.queryList(postQuery);
		if (postList != null && !postList.isEmpty()) {
			Post post = postList.get(0);
			long commentCount = post.getCommentCount();
			commentCount++;
			post.setCommentCount(commentCount);
			postService.update(post);
		}

		return "OK";
	}

	public String deleteComment() throws Exception {

		HttpSession session = WebTools.getHttpSession();
		User loginUser = (User) session.getAttribute(WPConstants.LOGIN_USER);
		if (loginUser == null) {
			return null;
		}

		Comment comment = new Comment();
		comment.setApproved("0");
		Date date = new Date();
		comment.setDate(date);
		comment.setDateGmt(date);
		// TODO
		PostQuery postQuery = new PostQuery();
		postQuery.setId(comment.getPostId());
		List<PostVO> postList = postService.queryList(postQuery);
		if (postList != null && !postList.isEmpty()) {
			Post post = postList.get(0);
			long commentCount = post.getCommentCount();
			commentCount--;
			if (commentCount >= 0) {
				post.setCommentCount(commentCount);
				postService.update(post);
			}
		}
		return null;
	}
}
